const projectId = '?auth_project_id=22'//苏州22,南通25，温州27，植发33
export const projectConfig = {
  mapKey: 'THQBZ-BNLKU-SQDVK-4D7JW-OPDIZ-GEBD7',
  mapName: '苏州瑞金白癜风医院',
  lat: '31.256083',
  lng: '120.641082'
}
//export const projectConfig = {
//   mapKey: 'PA7BZ-K7ELX-XE34Y-7VSXK-OFCM3-2KF6O',
//   mapName: '温州中研白癜风专科',
//   lat: '27.972934',
//   lng: '120.750142'
// }
//export const projectConfig = {
//   mapKey:'TCVBZ-EMLC4-K3BU7-XR77R-YBJOE-TKB3L',
//   mapName: '曙光毛发卫士',
//   lat: '31.861003',
//   lng: '117.277312'
// }
// export const projectConfig = {
//   mapKey: 'PTCBZ-WCVYJ-KC3F4-F3HWD-XPG4T-LMBHC',
//   mapName: '南通复大皮肤病专科门诊部',
//   lat: '32.020314',
//   lng: '120.881175'
// }
// const baseUrl ='https://momo-manager-test.api.ahjgyl.com'  //测试域名
const baseUrl = 'https://momo-manager.api.ahjgyl.com'
const bannerUrl = '/mini/active/ad-navbar/index'          //首页banner
const caseUrl = '/mini/video/video/'          //首页康复案例
const activeUrl = '/mini/active/active/index'          //首页公益活动
const activeDetailUrl = '/mini/active/active/active-detail'          //活动详情
const doctorUrl = '/mini/doctor/doctor/recommend-list'          //首页推荐专家
const doctorListUrl = '/mini/doctor/doctor/list'          //医生列表
const doctorDetailUrl = '/mini/doctor/doctor/info'          //医生详情
const arcListUrl = '/mini/content/arc/arc-list'          //首页文章列表
const channelUrl = '/mini/content/lists/get-list'          //文章栏目
const listUrl = '/mini/content/arc/get-arc-by-list'          //文章列表
const arcDetailUrl = '/mini/content/arc/get-arc-by-id'          //文章详情
const helpUrl = '/mini/patient/patient/problem'          //帮助中心
const openIdUrl ='/mini/site/get-openid'                //获取openid
const loginUrl ='/mini/site/login'                       //登录
const profileUrl = '/mini/patient/patient/my-index'       //我的首页   
const patientListUrl = '/mini/patient/patient/list'       //就诊人列表  
const appointmentUrl = '/mini/patient/appointment/list'       //预约人列表  
const addPatientUrl = '/mini/patient/patient/add-patient'       //添加就诊人  
const delPatientUrl = '/mini/patient/patient/del-patient'       //删除就诊人  
const orderDetailUrl = '/mini/doctor/doctor/order-info'          //医生预约详情
const orderCreateUrl = '/mini/doctor/doctor/create'          //预约
const orderDelUrl = '/mini/patient/appointment/cancel'          //预约取消
const yyjsUrl = '/mini/active/ad-navbar/hospital'          //医院介绍
const lastVisitoeUrl = '/mini/patient/patient/last-time'          //统计最后一次访问时间
const singleUrl = "/mini/active/ad-navbar/get-lists-view"       //单页
const getPhoneUrl ="/mini/site/get-tel"                        //获取手机号
export const uploadUrl = baseUrl + '/mini/upload/images' + projectId   //头像上传地址
 


function getopenId(data, type) {
  return new Promise(function (resolve, reject) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.request({
      url: baseUrl + openIdUrl + projectId,
      data: data,
      method: type,
      header: {
        'content-type': 'application/json', // 默认值
        'Cache-Control': 'max-age=180'
      },
      success: function (res) {
        resolve(res)
        wx.hideLoading()
      },
      fail: function (err) {
        //服务器连接异常
        reject(err, "服务器连接异常，请检查网络再试")
      },
    })
  });
}
export function getTel(e) {
  wx.login({
    success(res) {
      if (res.code) {
        let code = res.code     
        getPhone(
          {
            code:code,
            encryptedData: e.detail.encryptedData,
            iv: e.detail.iv
          },
          'post'
        ).then(res => {
          wx.setStorageSync('tel', res.data)
          if (e.currentTarget.dataset.url){
            if (e.currentTarget.dataset.url.indexOf('?')>0){
              wx.navigateTo({
                url: e.currentTarget.dataset.url + "&tel=" + res.data,
              })
            }else{
              wx.navigateTo({
                url: e.currentTarget.dataset.url + "?tel=" + res.data,
              })
            }            
          }
        })
      }
    }
  })
}
function getPhone(data, type) {
  return request(getPhoneUrl, data, type)
}
function getToken(data, type) {
  return request(loginUrl, data, type)
}
export function login(tohome=true,url) {
  let path = getCurrentPages().pop()
  let query = path.options
  let params = ''
  for (let i in query) {
    params += i + '=' + query[i] + '&'
  }
  let that = this;
  // 获取用户头像昵称
  wx.getUserProfile({
    desc: '用于完善用户资料',
    success: (res) => {
      let userInfo = res.userInfo
      // 登录
      wx.login({
        success(res) {
          if (res.code) {
            getopenId({ code: res.code }).then(res => {
              wx.setStorageSync('openId', res.data.data.openid)
              getToken(
                {
                  openid: res.data.data.openid,
                  nickname: userInfo.nickName,
                  head_portrait: userInfo.avatarUrl
                },
                'post'
              ).then(res => {
                wx.setStorageSync('userinfo', res.data.member)
                // 将后端返回的token存储到本地
                wx.setStorageSync('token', res.data.access_token)
                if (res.data.template){
                  let successTem = ''
                  let cancelTem = ''
                  res.data.template.forEach(item => {
                    if (item.type == 1) {
                      successTem = item.template_id
                    } else {
                      cancelTem = item.template_id
                    }                  
                  })
                  wx.setStorageSync('successTem', successTem)
                  wx.setStorageSync('cancelTem', cancelTem)
                }
                
                
                wx.setStorageSync('isLogin', true)    
                if (url){
                  wx.navigateTo({
                    url: url
                  })
                }else{
                  wx.reLaunch({
                    url: '/' + path.route + '?' + params
                  })
                }         
                
              })
            })
          }
        }
      })
    }, fail: (rej) => {
      if (tohome){
        wx.switchTab({
          url: '/pages/home/home'
        })
      }
     
    }
  })
}

export function login2(userInfo,tohome = true, url) {
  let path = getCurrentPages().pop()
  let query = path.options
  let params = ''
  for (let i in query) {
    params += i + '=' + query[i] + '&'
  }
  let that = this;
  // 获取用户头像昵称
      // 登录
      wx.login({
        success(res) {
          if (res.code) {
            getopenId({ code: res.code }).then(res => {
              wx.setStorageSync('openId', res.data.data.openid)
              let parms
              if (userInfo){
                parms = {
                  openid: res.data.data.openid,
                  nickname: userInfo.nickName,
                  head_portrait: userInfo.avatarUrl
                }
              }else{
                parms = {
                  openid: res.data.data.openid
                }
              }              
              getToken(
                parms,
                'post'
              ).then(res => {
                wx.setStorageSync('userinfo', res.data.member)
                // 将后端返回的token存储到本地
                wx.setStorageSync('token', res.data.access_token)
                if (res.data.template) {
                  let successTem = ''
                  let cancelTem = ''
                  res.data.template.forEach(item => {
                    if (item.type == 1) {
                      successTem = item.template_id
                    } else {
                      cancelTem = item.template_id
                    }
                  })
                  wx.setStorageSync('successTem', successTem)
                  wx.setStorageSync('cancelTem', cancelTem)
                }
                wx.setStorageSync('isLogin', true)
                if (url) {
                  wx.navigateTo({
                    url: url
                  })
                } else {
                  wx.reLaunch({
                    url: '/' + path.route + '?' + params
                  })
                }

              })
            })
          }
        }
      })
}






function request (url,data,type='get') {
  let token = wx.getStorageSync('userinfo') ? '&auth_access_token=' + wx.getStorageSync('token') : ''
  return new Promise(function (resolve, reject) {
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    wx.request({
      url: baseUrl + url + projectId + token,
      data: data,
      method: type,
      header: {
        'content-type': 'application/json', // 默认值
        'Cache-Control': 'max-age=180'
      },
      success: function (res) {
        if(res.data.code==200){
          resolve(res.data)  
          wx.hideLoading()        
        } else if (res.data.code == 401){          
          wx.setStorageSync('userinfo', '')
          // 将后端返回的token存储到本地
          wx.setStorageSync('token', '')
          wx.setStorageSync('isLogin', false)
          wx.hideLoading()
          return;
        }else{
          wx.hideLoading()
          if(res.data.code!=500){
            wx.showToast({
              title: res.data.message,
              icon: 'none',
              duration: 3000
            })
          }
          return;
        }
        
      },
      fail: function (err) {
        //服务器连接异常
        reject(err, "服务器连接异常，请检查网络再试")
      },
    })
  });
}
export { baseUrl }
export function bannerArr() {
  return request(bannerUrl)
}
export function getCase(data,type) {
  return request(caseUrl,data,type)
}
export function getActive(data, type) {
  return request(activeUrl, data, type)
}
export function getActiveDetail(data, type) {
  return request(activeDetailUrl, data, type)
}
export function getDoctor(data, type) {
  return request(doctorUrl, data, type)
}
export function getDoctorList(data, type) {
  return request(doctorListUrl, data, type)
}
export function getDoctorDetail(data, type) {
  return request(doctorDetailUrl, data, type)
}

export function getArcList(data, type) {
  return request(arcListUrl, data, type)
}
export function getChannel(data, type) {
  return request(channelUrl, data, type)
}
export function getList(data, type) {
  return request(listUrl, data, type)
} 
export function getArcDetail(data, type) {
  return request(arcDetailUrl, data, type)
}
export function getHelp(data, type) {
  return request(helpUrl, data, type)
} 
export function getProfile(data, type) {
  return request(profileUrl, data, type)
}

export function getPatientList(data, type) {
  return request(patientListUrl, data, type)
} 
export function getAppointment(data, type) {
  return request(appointmentUrl, data, type)
}
export function addPatient(data, type) {
  return request(addPatientUrl, data, type)
}
export function delPatient(data, type) {
  return request(delPatientUrl, data, type)
}
export function orderDetail(data, type) {
  return request(orderDetailUrl, data, type)
}

export function orderCreate(data, type) {
  return request(orderCreateUrl, data, type)
}
export function orderDel(data, type) {
  return request(orderDelUrl, data, type)
}
export function getHospital(data, type) {
  return request(yyjsUrl, data, type)
}
export function getsingle(data, type){
  return request(singleUrl, data, type)
}
export function lastVisitor(data, type) {
  return request(lastVisitoeUrl, data, type)
}
export function homeGetTel(e) {
  wx.login({
    success(res) {
      if (res.code) {
        getopenId({ code: res.code }).then(res => {
          wx.setStorageSync('openId', res.data.data.openid)
          let parms = {
            openid: res.data.data.openid
          }
          getToken(
            parms,
            'post'
          ).then(res => {
            wx.setStorageSync('userinfo', res.data.member)
            // 将后端返回的token存储到本地
            wx.setStorageSync('token', res.data.access_token)
            wx.login({
              success(res) {
                if (res.code) {
                  let code = res.code
                  getPhone(
                    {
                      code: code,
                      encryptedData: e.detail.encryptedData,
                      iv: e.detail.iv
                    },
                    'post'
                  ).then(res => {
                    let path = getCurrentPages().pop()
                    let query = path.options
                    let params = ''
                    for (let i in query) {
                      params += i + '=' + query[i] + '&'
                    }
                    wx.setStorageSync('tel', res.data)
                    wx.reLaunch({
                      url: '/' + path.route + '?' + params
                    })
                   
                  })
                }
              }
            })

          })
        })
      }
    }
  })
}

function change(t) {
  if (t < 10) {
    return "0" + t;
  } else {
    return t;
  }
}
export function formatDate(date) {
  let year = date.getFullYear()
  let month = change(date.getMonth() + 1)
  let day = change(date.getDate())
  return year + '-' + month + '-' + day;
}
function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}
export function visions(date) {
  const version = wx.getSystemInfoSync().SDKVersion
  let visionShow = 0
  wx.login({
    success(res) {
      if (res.code) {
        getopenId({ code: res.code }).then(res1 => {           
          if (compareVersion(version, '2.27.0') > 0) {
            visionShow=1
            if (!res1.data.data.type) {
              visionShow = 2
            }
          }
          wx.setStorageSync('visionShow', visionShow)
          return visionShow
        })
      }
    }
  })
  
  
}
